package com.bawei.lib_storage.room

import android.util.Log
import com.bawei.lib_storage.room.entity.FavoriteEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * 收藏管理工具类
 */
object FavoriteManager {
    
    private const val TAG = "FavoriteManager"
    
    /**
     * 添加收藏
     */
    suspend fun addFavorite(
        userId: String,
        videoId: String,
        title: String,
        primaryImg: String,
        content: String,
        authorImg: String,
        authorName: String,
        videoPath: String,
        channelId: String
    ): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                // 检查是否已经收藏
                val existingCount = DBUtils.getDB().favoriteDao().isFavorite(userId, videoId)
                if (existingCount > 0) {
                    Log.d(TAG, "视频已收藏，跳过添加: $title")
                    return@withContext true
                }
                
                val favoriteEntity = FavoriteEntity(
                    userId = userId,
                    videoId = videoId,
                    title = title,
                    primaryImg = primaryImg,
                    content = content,
                    authorImg = authorImg,
                    authorName = authorName,
                    videoPath = videoPath,
                    channelId = channelId
                )
                
                DBUtils.getDB().favoriteDao().insert(favoriteEntity)
                Log.d(TAG, "添加收藏成功: $title, 用户ID: $userId")
                true
            } catch (e: Exception) {
                Log.e(TAG, "添加收藏失败: ${e.message}", e)
                false
            }
        }
    }
    
    /**
     * 移除收藏
     */
    suspend fun removeFavorite(userId: String, videoId: String): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                DBUtils.getDB().favoriteDao().deleteByUserIdAndVideoId(userId, videoId)
                Log.d(TAG, "移除收藏成功，用户ID: $userId, 视频ID: $videoId")
                true
            } catch (e: Exception) {
                Log.e(TAG, "移除收藏失败: ${e.message}", e)
                false
            }
        }
    }
    
    /**
     * 检查是否已收藏
     */
    suspend fun isFavorite(userId: String, videoId: String): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                val count = DBUtils.getDB().favoriteDao().isFavorite(userId, videoId)
                count > 0
            } catch (e: Exception) {
                Log.e(TAG, "检查收藏状态失败: ${e.message}", e)
                false
            }
        }
    }
    
    /**
     * 获取用户收藏列表
     */
    suspend fun getFavoriteListByUserId(userId: String): List<FavoriteEntity> {
        return withContext(Dispatchers.IO) {
            try {
                val list = DBUtils.getDB().favoriteDao().getAllByUserId(userId)
                Log.d(TAG, "获取用户收藏列表成功，用户ID: $userId, 数量: ${list.size}")
                list
            } catch (e: Exception) {
                Log.e(TAG, "获取用户收藏列表失败: ${e.message}", e)
                emptyList()
            }
        }
    }
    
    /**
     * 分页获取用户收藏列表
     */
    suspend fun getFavoriteListByUserIdAndPage(userId: String, page: Int, pageSize: Int): List<FavoriteEntity> {
        return withContext(Dispatchers.IO) {
            try {
                val list = DBUtils.getDB().favoriteDao().getAllByUserIdAndPage(userId, page, pageSize)
                Log.d(TAG, "分页获取用户收藏列表成功，用户ID: $userId, 页码: $page, 数量: ${list.size}")
                list
            } catch (e: Exception) {
                Log.e(TAG, "分页获取用户收藏列表失败: ${e.message}", e)
                emptyList()
            }
        }
    }
    
    /**
     * 搜索收藏
     */
    suspend fun searchFavorites(userId: String, keywords: String): List<FavoriteEntity> {
        return withContext(Dispatchers.IO) {
            try {
                val list = DBUtils.getDB().favoriteDao().searchByKeywords(userId, keywords)
                Log.d(TAG, "搜索收藏成功，用户ID: $userId, 关键词: $keywords, 数量: ${list.size}")
                list
            } catch (e: Exception) {
                Log.e(TAG, "搜索收藏失败: ${e.message}", e)
                emptyList()
            }
        }
    }
    
    /**
     * 删除指定收藏
     */
    suspend fun deleteFavorite(favoriteEntity: FavoriteEntity) {
        withContext(Dispatchers.IO) {
            try {
                DBUtils.getDB().favoriteDao().delete(favoriteEntity)
                Log.d(TAG, "删除收藏成功: ${favoriteEntity.title}")
            } catch (e: Exception) {
                Log.e(TAG, "删除收藏失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 清空用户所有收藏
     */
    suspend fun clearAllFavoritesByUserId(userId: String) {
        withContext(Dispatchers.IO) {
            try {
                DBUtils.getDB().favoriteDao().deleteAllByUserId(userId)
                Log.d(TAG, "清空用户收藏成功，用户ID: $userId")
            } catch (e: Exception) {
                Log.e(TAG, "清空用户收藏失败: ${e.message}", e)
            }
        }
    }
    
    /**
     * 清空所有收藏
     */
    suspend fun clearAllFavorites() {
        withContext(Dispatchers.IO) {
            try {
                DBUtils.getDB().favoriteDao().deleteAll()
                Log.d(TAG, "清空所有收藏成功")
            } catch (e: Exception) {
                Log.e(TAG, "清空所有收藏失败: ${e.message}", e)
            }
        }
    }
} 